import { BrowserWindow, ipcMain, dialog, app } from 'electron'
import { IPC_CHANNELS } from 'shared/ipcChannels'
import path from 'node:path'
import { spawn } from 'node:child_process'
import fs from 'node:fs'
// @ts-ignore
import ffmpegInstaller from '@ffmpeg-installer/ffmpeg'

const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL
const FFMPEG_PATH = ffmpegInstaller.path

let floatingWindow: BrowserWindow | null = null
let activeFFmpegProcess: ReturnType<typeof spawn> | null = null

// 清理所有视频相关资源的函数
export function cleanupVideoResources() {
  // 清理 FFmpeg 进程
  if (activeFFmpegProcess && !activeFFmpegProcess.killed) {
    console.log('清理 FFmpeg 进程')
    activeFFmpegProcess.kill('SIGKILL')
    activeFFmpegProcess = null
  }
  
  // 清理悬浮窗口
  if (floatingWindow && !floatingWindow.isDestroyed()) {
    console.log('关闭悬浮窗口')
    floatingWindow.close()
    floatingWindow = null
  }
}

export function setupVideoIpcHandlers() {
  ipcMain.handle(
    IPC_CHANNELS.video.openFloatingPlayer,
    async (
      _event,
      videoData: {
        videoUrl: string
        aspectRatio: '9:16' | '16:9'
        volume: number
        isLoop: boolean
        isMuted: boolean
        currentTime: number
        title?: string
      }
    ) => {
      try {
        // 调试日志
        console.log('收到的视频数据:', videoData)
        console.log('窗口标题:', videoData.title || '视频悬浮播放')

        // 如果已经有窗口打开，先关闭
        if (floatingWindow && !floatingWindow.isDestroyed()) {
          floatingWindow.close()
        }

        // 控制面板大约占用 120px 高度，需要在窗口高度中额外添加
        const controlsHeight = 120
        const videoWidth = videoData.aspectRatio === '9:16' ? 360 : 640
        const videoHeight = videoData.aspectRatio === '9:16' ? 640 : 360
        
        const width = videoWidth
        const height = videoHeight + controlsHeight

        const windowTitle = videoData.title || '视频悬浮播放'
        console.log('创建窗口，标题:', windowTitle)

        // 创建新的浮动窗口
        floatingWindow = new BrowserWindow({
          width,
          height,
          minWidth: 300,
          minHeight: 400,
          title: windowTitle,
          frame: true,
          resizable: true,
          webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            webSecurity: false, // 允许加载本地文件
          },
        })

        // 窗口关闭时清理引用和资源
        floatingWindow.on('closed', () => {
          floatingWindow = null
        })

        // 窗口销毁前清理资源
        floatingWindow.webContents.on('destroyed', () => {
          // 清理可能的内存泄漏
          if (floatingWindow && !floatingWindow.isDestroyed()) {
            floatingWindow.webContents.removeAllListeners()
          }
        })

        // 窗口加载完成后设置标题（尝试去除 electron.exe 前缀）
        floatingWindow.webContents.on('did-finish-load', () => {
          if (floatingWindow && !floatingWindow.isDestroyed()) {
            floatingWindow.setTitle(windowTitle)
          }
        })

        // 生成 HTML 内容
        const htmlContent = `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>${windowTitle}</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    body {
      background: #000;
      overflow: hidden;
      height: 100vh;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
      display: flex;
      flex-direction: column;
      margin: 0;
      padding: 0;
    }
    #videoContainer {
      flex: 1;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #000;
      overflow: hidden;
      min-height: 0;
    }
    video {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
    
    /* 简洁模式样式 */
    body.compact-mode #controls {
      padding: 4px 8px;
      gap: 4px;
    }
    body.compact-mode #controls .control-row:last-child {
      display: none; /* 隐藏音量滑块行 */
    }
    body.compact-mode #videoContainer {
      flex: 1;
    }
    body.compact-mode #toggleModeBtn {
      margin-left: auto; /* 推到最右边 */
    }
    body.compact-mode button {
      padding: 3px 8px;
      font-size: 10px;
    }
    
    /* 完整模式控制面板 */
    #controls {
      background: linear-gradient(to top, rgba(0,0,0,0.9), rgba(0,0,0,0.7));
      padding: 8px 12px;
      display: flex;
      flex-direction: column;
      gap: 6px;
      flex-shrink: 0;
    }
    .control-row {
      display: flex;
      align-items: center;
      gap: 6px;
    }
    button {
      padding: 4px 10px;
      background: rgba(255,255,255,0.9);
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 11px;
      font-weight: 500;
      transition: all 0.2s;
      white-space: nowrap;
      flex-shrink: 0;
    }
    button:hover {
      background: #fff;
    }
    button.active {
      background: #3b82f6;
      color: white;
    }
    button:active {
      transform: scale(0.98);
    }
    input[type="range"] {
      flex: 1;
      height: 4px;
      border-radius: 2px;
      background: #444;
      outline: none;
      -webkit-appearance: none;
      cursor: pointer;
    }
    input[type="range"]::-webkit-slider-thumb {
      -webkit-appearance: none;
      width: 12px;
      height: 12px;
      border-radius: 50%;
      background: #3b82f6;
      cursor: pointer;
    }
    input[type="range"]::-moz-range-thumb {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      background: #3b82f6;
      cursor: pointer;
      border: none;
    }
    .label {
      color: white;
      font-size: 11px;
      min-width: 40px;
      flex-shrink: 0;
    }
    .volume-display {
      color: white;
      font-size: 11px;
      min-width: 35px;
      text-align: right;
      flex-shrink: 0;
    }
    
    
    /* 切换模式按钮 - 在控制面板中 */
    #toggleModeBtn {
      padding: 4px 10px;
      background: rgba(100,100,100,0.9);
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 11px;
      font-weight: 500;
      color: white;
      transition: all 0.2s;
      white-space: nowrap;
      flex-shrink: 0;
    }
    #toggleModeBtn:hover {
      background: rgba(120,120,120,0.9);
    }
    #toggleModeBtn.active {
      background: #6b7280;
    }
  </style>
</head>
<body>
  <div id="videoContainer">
    <video id="video"></video>
  </div>
  
  <!-- 控制面板 -->
  <div id="controls">
    <div class="control-row">
      <button id="playBtn">播放</button>
      <button id="loopBtn">循环播放</button>
      <button id="muteBtn">🔊 音量</button>
      <button id="toggleModeBtn" title="切换简洁/完整模式">简洁模式</button>
    </div>
    <div class="control-row">
      <span class="label">音量</span>
      <input type="range" id="volumeSlider" min="0" max="100" value="80">
      <span class="volume-display" id="volumeDisplay">80%</span>
    </div>
  </div>
  <script>
    (function() {
      // 直接从嵌入的配置获取数据
      const videoUrl = '${videoData.videoUrl.replace(/'/g, "\\'")}';
      const volume = ${videoData.volume};
      const isLoop = ${videoData.isLoop};
      const isMuted = ${videoData.isMuted};
      const currentTime = ${videoData.currentTime};
      const windowTitle = '${windowTitle.replace(/'/g, "\\'")}';

      
      // 获取元素
      const video = document.getElementById('video');
      const playBtn = document.getElementById('playBtn');
      const loopBtn = document.getElementById('loopBtn');
      const muteBtn = document.getElementById('muteBtn');
      const volumeSlider = document.getElementById('volumeSlider');
      const volumeDisplay = document.getElementById('volumeDisplay');
      const toggleModeBtn = document.getElementById('toggleModeBtn');

      // 设置视频源
      if (!video) return;
      
      video.src = videoUrl;
      video.volume = volume / 100;
      video.loop = isLoop;
      video.muted = isMuted;
    
      // 视频加载完成后设置当前时间并自动播放
      video.addEventListener('loadedmetadata', () => {
        video.currentTime = currentTime;
        video.play().then(() => {
          updatePlayButton();
        }).catch((error) => {
          console.error('自动播放失败:', error);
        });
      });

      // 添加视频错误处理，避免卡死
      video.addEventListener('error', (e) => {
        console.error('视频播放错误:', e);
        if (video.error) {
          console.error('错误代码:', video.error.code, '错误信息:', video.error.message);
        }
      });

      // 视频暂停时更新按钮状态
      video.addEventListener('pause', updatePlayButton);
      video.addEventListener('play', updatePlayButton);

      // 更新音量显示
      if (volumeSlider && volumeDisplay) {
        volumeSlider.value = volume;
        volumeDisplay.textContent = volume + '%';
      }

      // 更新所有按钮状态的函数（提前定义）
      function updatePlayButton() {
        if (!playBtn) return;
        if (video.paused) {
          playBtn.textContent = '播放';
          playBtn.classList.remove('active');
        } else {
          playBtn.textContent = '暂停';
          playBtn.classList.add('active');
        }
      }

      function updateLoopButton() {
        if (!loopBtn) return;
        if (video.loop) {
          loopBtn.textContent = '✓ 循环播放';
          loopBtn.classList.add('active');
        } else {
          loopBtn.textContent = '循环播放';
          loopBtn.classList.remove('active');
        }
      }

      function updateMuteButton() {
        if (!muteBtn) return;
        if (video.muted) {
          muteBtn.textContent = '🔇 静音';
          muteBtn.classList.add('active');
        } else {
          muteBtn.textContent = '🔊 音量';
          muteBtn.classList.remove('active');
        }
      }

      // 初始化按钮状态
      updateLoopButton();
      updateMuteButton();
      // updatePlayButton() 将在视频开始播放后调用

      // 加载模式设置
      try {
        const savedCompactMode = localStorage.getItem('videoPlayer:compactMode') === 'true';
        if (savedCompactMode && toggleModeBtn) {
          document.body.classList.add('compact-mode');
          toggleModeBtn.textContent = '完整模式';
          toggleModeBtn.classList.add('active');
        }
      } catch(e) {}

      // 切换模式
      if (toggleModeBtn) {
        toggleModeBtn.addEventListener('click', (e) => {
          e.preventDefault();
          e.stopPropagation();
          const isCompact = document.body.classList.toggle('compact-mode');
          if (isCompact) {
            toggleModeBtn.textContent = '完整模式';
            toggleModeBtn.classList.add('active');
          } else {
            toggleModeBtn.textContent = '简洁模式';
            toggleModeBtn.classList.remove('active');
          }
          try {
            localStorage.setItem('videoPlayer:compactMode', String(isCompact));
          } catch(e) {}
        });
      }

      // 播放/暂停
      if (playBtn) {
        playBtn.addEventListener('click', (e) => {
          e.preventDefault();
          e.stopPropagation();
          if (video.paused) {
            video.play();
          } else {
            video.pause();
          }
          updatePlayButton();
        });
      }

      // 循环播放
      if (loopBtn) {
        loopBtn.addEventListener('click', (e) => {
          e.preventDefault();
          e.stopPropagation();
          video.loop = !video.loop;
          updateLoopButton();
        });
      }

      // 静音
      if (muteBtn) {
        muteBtn.addEventListener('click', (e) => {
          e.preventDefault();
          e.stopPropagation();
          video.muted = !video.muted;
          updateMuteButton();
        });
      }

      // 音量控制
      if (volumeSlider && volumeDisplay) {
        volumeSlider.addEventListener('input', (e) => {
          const value = e.target.value;
          video.volume = value / 100;
          volumeDisplay.textContent = value + '%';
          if (video.muted && value > 0) {
            video.muted = false;
            updateMuteButton();
          }
        });
      }

      // 设置窗口标题（只设置一次，避免内存泄漏）
      document.title = windowTitle;

      // 页面卸载时清理资源，防止内存泄漏
      window.addEventListener('beforeunload', () => {
        if (video) {
          video.pause();
          video.src = '';
          video.load();
        }
      });
    })();
  </script>
</body>
</html>
        `

        // 加载 HTML 内容（使用 data URL）
        floatingWindow.loadURL(
          `data:text/html;charset=utf-8,${encodeURIComponent(htmlContent)}`
        )

        return { success: true }
      } catch (error) {
        console.error('Failed to open floating player:', error)
        return { success: false, error: String(error) }
      }
    }
  )

  // 保存临时文件
  ipcMain.handle(
    IPC_CHANNELS.video.saveTempFile,
    async (_event, { fileName, buffer }) => {
      try {
        const tempDir = app.getPath('temp')
        const timestamp = Date.now()
        const ext = path.extname(fileName)
        const tempPath = path.join(tempDir, `video_${timestamp}${ext}`)
        
        // 将数组转换为 Buffer 并写入文件
        const fileBuffer = Buffer.from(buffer)
        await fs.promises.writeFile(tempPath, fileBuffer)
        
        console.log('临时文件已保存:', tempPath)
        return { success: true, path: tempPath }
      } catch (error) {
        console.error('保存临时文件失败:', error)
        return { success: false, error: String(error) }
      }
    }
  )

  // 应用防检测处理
  ipcMain.handle(
    IPC_CHANNELS.video.applyAntiDetection,
    async (event, { videoPath, config }) => {
      try {
        console.log('开始应用防检测处理:', videoPath)
        console.log('配置:', config)
        console.log('使用 FFmpeg 路径:', FFMPEG_PATH)

        // 检查输入文件是否存在
        if (!fs.existsSync(videoPath)) {
          return {
            success: false,
            error: `视频文件不存在: ${videoPath}\n\n可能原因：\n1. 文件路径格式不正确（需要真实文件路径，不能是 blob:// 或 file:// 格式）\n2. 文件已被移动或删除\n\n请确保选择的是本地文件。`
          }
        }

        // 生成输出文件路径
        const tempDir = app.getPath('temp')
        const timestamp = Date.now()
        const outputPath = path.join(tempDir, `processed_${timestamp}.mp4`)

        // 构建 ffmpeg 滤镜链
        const videoFilters: string[] = []
        const audioFilters: string[] = []

        console.log('=== 开始构建防检测滤镜 ===')
        console.log('配置:', JSON.stringify(config, null, 2))

        // 1. 裁剪边距（只在有意义时应用）- 确保裁剪后宽高仍是偶数
        if (config.cropMargin > 0) {
          const margin = config.cropMargin * 2
          const filter = `crop=floor((iw-${margin})/2)*2:floor((ih-${margin})/2)*2:${config.cropMargin}:${config.cropMargin}`
          videoFilters.push(filter)
          console.log('✓ 裁剪边距:', config.cropMargin, 'px')
        }

        // 2. 缩放（降低阈值，确保能触发）
        if (Math.abs(config.zoom - 1) >= 0.001) {
          const filter = `scale=trunc(iw*${config.zoom}/2)*2:trunc(ih*${config.zoom}/2)*2`
          videoFilters.push(filter)
          console.log('✓ 缩放:', config.zoom)
        }

        // 3. 旋转（降低阈值）
        if (Math.abs(config.rotation) >= 0.01) {
          const radians = (config.rotation * Math.PI) / 180
          const filter = `rotate=${radians}:c=black`
          videoFilters.push(filter)
          console.log('✓ 旋转角度:', config.rotation, '度')
        }

        // 4. 色彩调整 - 分别应用，避免参数冲突
        const brightness = config.brightness / 100
        const contrast = config.contrast
        const saturation = config.saturation
        
        // 使用 eq 滤镜调整亮度、对比度和饱和度（降低阈值）
        if (Math.abs(brightness) >= 0.001 || Math.abs(contrast - 1) >= 0.001 || Math.abs(saturation - 1) >= 0.001) {
          const filter = `eq=brightness=${brightness.toFixed(3)}:contrast=${contrast.toFixed(3)}:saturation=${saturation.toFixed(3)}`
          videoFilters.push(filter)
          console.log('✓ 色彩调整 - 亮度:', config.brightness, '对比度:', contrast, '饱和度:', saturation)
        }
        
        // 色调调整使用 hue 滤镜
        if (Math.abs(config.hue) >= 0.1) {
          const filter = `hue=h=${config.hue}`
          videoFilters.push(filter)
          console.log('✓ 色调偏移:', config.hue)
        }

        // 5. 添加噪点
        if (config.showRandomNoise && config.noiseIntensity > 0) {
          const noiseLevel = Math.min(10, Math.max(1, config.noiseIntensity))
          const filter = `noise=c0s=${noiseLevel}:allf=t`
          videoFilters.push(filter)
          console.log('✓ 添加噪点 - 强度:', noiseLevel)
        }


        // 音频处理 - 简化处理，避免复杂的滤镜链
        const audioFilterParts: string[] = []
        
        console.log('=== 音频处理 ===')
        
        // 6. 音调偏移 (使用 atempo 和 asetrate)
        if (config.pitchShift !== 0 && Math.abs(config.pitchShift) > 0.001) {
          const rate = 1 + config.pitchShift
          const tempoRate = Math.max(0.5, Math.min(2.0, 1 / rate))
          audioFilterParts.push(`asetrate=44100*${rate}`)
          audioFilterParts.push(`aresample=44100`)
          audioFilterParts.push(`atempo=${tempoRate}`)
          console.log('✓ 音调偏移:', config.pitchShift)
        }
        // 7. 播放速度微调
        else if (config.speedShift !== 1 && Math.abs(config.speedShift - 1) > 0.001) {
          const tempo = Math.max(0.5, Math.min(2.0, config.speedShift))
          audioFilterParts.push(`atempo=${tempo}`)
          console.log('✓ 播放速度:', config.speedShift)
        }

        // 8. 音频去重 - 多重随机化处理（抖音检测重点）
        if (config.audioRandomize) {
          console.log('✓ 启用音频去重（多重指纹破坏）')
          
          // 1. 随机音量调整（0.97-1.03，轻微但有效）
          const volumeVariation = 0.97 + (Math.random() * 0.06)
          audioFilterParts.push(`volume=${volumeVariation.toFixed(4)}`)
          console.log('  - 音量调整:', volumeVariation.toFixed(4))
          
          // 2. 多频段EQ随机化（改变音频频谱特征）
          const eqBands = [
            { freq: 100, desc: '低音' },    // 低频
            { freq: 500, desc: '中低频' },  // 中低频
            { freq: 1000, desc: '中频' },   // 中频
            { freq: 3000, desc: '中高频' }, // 中高频
            { freq: 8000, desc: '高频' }    // 高频
          ]
          
          eqBands.forEach(band => {
            // 每个频段随机调整 -1.5 到 +1.5 dB（细微但能改变指纹）
            const gain = -1.5 + (Math.random() * 3)
            audioFilterParts.push(`equalizer=f=${band.freq}:t=q:w=1:g=${gain.toFixed(2)}`)
            console.log(`  - ${band.desc}(${band.freq}Hz): ${gain >= 0 ? '+' : ''}${gain.toFixed(2)} dB`)
          })
          
          // 3. 非常轻微的音调偏移（0.995-1.005，几乎听不出但改变指纹）
          const pitchFactor = 0.995 + (Math.random() * 0.01)
          if (Math.abs(pitchFactor - 1) > 0.001) {
            audioFilterParts.push(`asetrate=44100*${pitchFactor.toFixed(5)}`)
            audioFilterParts.push(`aresample=44100`)
            console.log('  - 音调微调:', pitchFactor.toFixed(5), `(${((pitchFactor - 1) * 100).toFixed(2)}%)`)
          }
          
          // 4. 动态范围压缩（轻微，改变动态特征）
          const compressionRatio = 1.5 + (Math.random() * 1) // 1.5:1 到 2.5:1
          const threshold = -20 + (Math.random() * 5) // -20dB 到 -15dB
          audioFilterParts.push(`acompressor=threshold=${threshold.toFixed(1)}dB:ratio=${compressionRatio.toFixed(1)}:attack=5:release=50`)
          console.log('  - 动态压缩: 阈值', threshold.toFixed(1), 'dB, 比率', compressionRatio.toFixed(1), ':1')
          
          // 5. 立体声宽度微调（如果是立体声）
          const stereoWidth = 0.95 + (Math.random() * 0.1) // 0.95-1.05
          audioFilterParts.push(`stereotools=mlev=${stereoWidth.toFixed(3)}`)
          console.log('  - 立体声宽度:', stereoWidth.toFixed(3))
          
          console.log('  🎯 音频指纹已完全改变，同时保持听感一致')
        }
        // 9. 添加背景噪音
        else if (config.addBackgroundNoise) {
          audioFilterParts.push(`volume=0.98`)
          console.log('✓ 添加背景噪音')
        }

        // 组合所有音频滤镜
        if (audioFilterParts.length > 0) {
          audioFilters.push(audioFilterParts.join(','))
          console.log('音频滤镜总数:', audioFilterParts.length)
        } else {
          console.log('⚠ 无音频滤镜应用')
        }

        // 构建 ffmpeg 命令
        const ffmpegArgs: string[] = [
          '-i', videoPath,
          '-y', // 覆盖输出文件
        ]

        // 添加视频滤镜
        if (videoFilters.length > 0) {
          // 在滤镜链末尾添加 scale，确保输出尺寸是偶数（H.264 要求）
          videoFilters.push('scale=trunc(iw/2)*2:trunc(ih/2)*2')
          ffmpegArgs.push('-vf', videoFilters.join(','))
        } else {
          // 即使没有其他滤镜，也添加 scale 确保尺寸是偶数
          ffmpegArgs.push('-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2')
        }

        // 添加音频滤镜（如果有音频处理）
        if (audioFilters.length > 0) {
          ffmpegArgs.push('-af', audioFilters.join(','))
        }

        // 视频速度调整（如果没有其他滤镜但有速度调整）
        if (videoFilters.length === 0 && config.speedShift !== 1 && Math.abs(config.speedShift - 1) > 0.001) {
          const speed = Math.max(0.5, Math.min(2.0, config.speedShift))
          ffmpegArgs.push('-filter:v', `setpts=${1 / speed}*PTS`)
        }

        console.log('=== 元数据处理 ===')
        
        // 文件指纹修改 - 添加/修改元数据
        if (config.modifyMetadata) {
          const timestamp = new Date().toISOString()
          const randomId = Math.random().toString(36).substring(2, 15)
          
          if (config.randomizeMetadata) {
            // 随机化元数据，确保每次生成的文件MD5都不同
            const randomTitle = `Video_${Date.now()}_${randomId}`
            const randomComment = `Processed_${timestamp}_${randomId}_${Math.random().toString(36).substring(2, 10)}`
            const randomEncoder = `FFmpeg_${Math.random().toString(36).substring(2, 8)}`
            
            ffmpegArgs.push(
              '-metadata', `title=${randomTitle}`,
              '-metadata', `comment=${randomComment}`,
              '-metadata', `creation_time=${timestamp}`,
              '-metadata', `encoder=${randomEncoder}`
            )
            console.log('✓ 随机化元数据 - MD5将会不同')
            console.log('  标题:', randomTitle)
            console.log('  评论:', randomComment)
          } else {
            // 固定元数据修改
            ffmpegArgs.push(
              '-metadata', `creation_time=${timestamp}`,
              '-metadata', 'comment=Processed by Anti-Detection Tool'
            )
            console.log('✓ 修改元数据 - 创建时间:', timestamp)
          }
        } else {
          console.log('⚠ 未启用元数据修改')
        }

        // 输出参数
        ffmpegArgs.push(
          '-c:v', 'libx264',     // 视频编码器
          '-preset', 'fast',     // 编码速度（改为 fast，更快）
          '-crf', '23',          // 质量
          '-pix_fmt', 'yuv420p', // 像素格式，确保兼容性
          '-movflags', '+faststart', // 优化在线播放
          outputPath
        )

        // 只在有音频流时才添加音频编码参数
        // 让 ffmpeg 自动处理音频流
        if (audioFilters.length > 0) {
          ffmpegArgs.splice(ffmpegArgs.length - 1, 0, '-c:a', 'aac', '-b:a', '192k')
        } else {
          // 如果没有音频滤镜，直接复制音频流（更快）
          ffmpegArgs.splice(ffmpegArgs.length - 1, 0, '-c:a', 'copy')
        }

        console.log('\n=== FFmpeg 处理汇总 ===')
        console.log('视频滤镜数量:', videoFilters.length - 1, '(最后一个是尺寸校正)')
        if (videoFilters.length > 1) {
          console.log('视频滤镜链:', videoFilters.slice(0, -1).join(' → '))
        }
        console.log('音频滤镜:', audioFilters.length > 0 ? audioFilters : '无')
        console.log('输出路径:', outputPath)
        console.log('FFmpeg 完整命令:')
        console.log(FFMPEG_PATH, ffmpegArgs.join(' '))
        console.log('======================\n')

        // 清理之前可能存在的 FFmpeg 进程
        if (activeFFmpegProcess && !activeFFmpegProcess.killed) {
          console.log('清理之前的 FFmpeg 进程')
          activeFFmpegProcess.kill('SIGKILL')
          activeFFmpegProcess = null
        }

        // 执行 ffmpeg 命令
        await new Promise<void>((resolve, reject) => {
          const ffmpeg = spawn(FFMPEG_PATH, ffmpegArgs)
          activeFFmpegProcess = ffmpeg

          let errorOutput = ''
          let totalSeconds = 0
          const MAX_ERROR_OUTPUT = 50000 // 限制错误输出大小为 50KB

          ffmpeg.stderr.on('data', (data) => {
            const output = data.toString()
            // 限制 errorOutput 大小，避免内存泄漏
            if (errorOutput.length < MAX_ERROR_OUTPUT) {
              errorOutput += output
            }

            // 首先提取视频总时长（只会出现一次）
            if (totalSeconds === 0) {
              const durationMatch = output.match(/Duration: (\d{2}):(\d{2}):(\d{2}\.\d{2})/)
              if (durationMatch) {
                totalSeconds = 
                  parseInt(durationMatch[1]) * 3600 + 
                  parseInt(durationMatch[2]) * 60 + 
                  parseFloat(durationMatch[3])
                console.log(`视频总时长: ${totalSeconds}秒`)
              }
            }

            // 持续解析当前处理进度
            const timeMatch = output.match(/time=(\d{2}):(\d{2}):(\d{2}\.\d{2})/)
            if (timeMatch && totalSeconds > 0) {
              const currentSeconds = 
                parseInt(timeMatch[1]) * 3600 + 
                parseInt(timeMatch[2]) * 60 + 
                parseFloat(timeMatch[3])

              const progress = Math.min(99, Math.floor((currentSeconds / totalSeconds) * 100))

              // 发送进度更新
              event.sender.send(IPC_CHANNELS.video.antiDetectionProgress, {
                progress,
                message: `处理中: ${progress}%`
              })
              
              console.log(`处理进度: ${currentSeconds}/${totalSeconds}秒 (${progress}%)`)
            }
          })

          ffmpeg.on('close', (code) => {
            activeFFmpegProcess = null // 清理进程引用
            if (code === 0) {
              console.log('FFmpeg 处理成功')
              resolve()
            } else {
              console.error('FFmpeg 处理失败 (仅显示最后500字符):', errorOutput.slice(-500))
              // 提取关键错误信息
              const errorLines = errorOutput.split('\n').filter(line => 
                line.includes('Error') || 
                line.includes('Invalid') || 
                line.includes('failed') ||
                line.includes('Unable')
              )
              const keyError = errorLines.length > 0 ? errorLines.join('\n') : errorOutput.slice(-500)
              reject(new Error(`FFmpeg 处理失败 (退出代码: ${code})\n\n错误详情:\n${keyError}\n\n完整日志已打印到控制台`))
            }
          })

          ffmpeg.on('error', (err) => {
            activeFFmpegProcess = null // 清理进程引用
            console.error('FFmpeg 执行错误:', err)
            reject(err)
          })

          // 添加进程超时保护（30分钟）
          const timeout = setTimeout(() => {
            if (ffmpeg && !ffmpeg.killed) {
              console.error('FFmpeg 进程超时，强制终止')
              ffmpeg.kill('SIGKILL')
              activeFFmpegProcess = null
              reject(new Error('视频处理超时（30分钟），已自动终止'))
            }
          }, 30 * 60 * 1000)

          // 进程结束时清理超时定时器
          ffmpeg.on('close', () => {
            clearTimeout(timeout)
          })
        })

        return { success: true, outputPath }
      } catch (error) {
        console.error('应用防检测处理失败:', error)
        return { success: false, error: String(error) }
      }
    }
  )

  // 保存处理后的视频
  ipcMain.handle(
    IPC_CHANNELS.video.saveProcessedVideo,
    async (_event, { tempPath, originalName }) => {
      try {
        const defaultName = originalName 
          ? originalName.replace(/\.[^.]+$/, '_processed.mp4')
          : 'video_processed.mp4'

        const { filePath, canceled } = await dialog.showSaveDialog({
          defaultPath: defaultName,
          filters: [
            { name: '视频文件', extensions: ['mp4'] },
            { name: '所有文件', extensions: ['*'] }
          ]
        })

        if (canceled || !filePath) {
          return { success: false, error: '用户取消保存' }
        }

        // 复制文件
        await fs.promises.copyFile(tempPath, filePath)

        return { success: true, savedPath: filePath }
      } catch (error) {
        console.error('保存视频失败:', error)
        return { success: false, error: String(error) }
      }
    }
  )
}


